package com.example.travel.Controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 功能：
 * 作者：lln
 * 日期：2025/3/17 14:24
 */
@RestController
@RequestMapping("/api")
public class WechatController {

    private static final Logger logger = LoggerFactory.getLogger(WechatController.class);

    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.appsecret}")
    private String appSecret;

    /**
     * 创建自定义的 RestTemplate，支持 text/plain 和 application/json 响应
     */
    private RestTemplate createRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        // 添加支持 text/plain 的转换器
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
        // 添加支持 application/json 的转换器
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        return restTemplate;
    }

    @RequestMapping(value = "/getSessionId", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<Map<String, String>> getSessionId(@RequestBody Map<String, String> requestBody) {
        String code = requestBody.get("code");
        if (code == null || code.isEmpty()) {
            logger.error("Code is missing in request body");
            return ResponseEntity.badRequest().body(Map.of("error", "Code is missing"));
        }

        logger.info("AppID: {}, AppSecret: {}", appId, appSecret); // 验证注入的值
        try {
            // 调用微信接口获取 openid 和 session_key
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={js_code}&grant_type={grant_type}";
            RestTemplate restTemplate = createRestTemplate();
            Map<String, String> params = new HashMap<>();
            params.put("appid", appId);
            params.put("secret", appSecret);
            params.put("js_code", code);
            params.put("grant_type", "authorization_code");

            logger.info("Calling WeChat API with params: {}", params);
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class, params);
            String responseBody = response.getBody();

            // 检查响应是否为空
            if (responseBody == null) {
                logger.error("WeChat API returned null body");
                return ResponseEntity.status(500).body(Map.of("error", "WeChat API returned null body"));
            }

            // 尝试将响应解析为 JSON
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> body = objectMapper.readValue(responseBody, Map.class);

                // 检查微信接口是否返回错误
                if (body.containsKey("errcode")) {
                    String errcode = body.get("errcode").toString();
                    String errmsg = body.get("errmsg").toString();
                    logger.error("WeChat API returned error: {} - {}", errcode, errmsg);
                    return ResponseEntity.status(500).body(Map.of("error", "WeChat API error: " + errmsg));
                }

                // 检查是否包含 openid 和 session_key
                if (body.containsKey("openid") && body.containsKey("session_key")) {
                    String openid = (String) body.get("openid");
                    String sessionKey = (String) body.get("session_key");
                    String sessionId = openid + "-" + sessionKey; // 生成自定义 sessionId

                    logger.info("Generated sessionId: {}", sessionId);
                    return ResponseEntity.ok(Map.of("sessionId", sessionId));
                } else {
                    logger.error("WeChat API response missing openid or session_key");
                    return ResponseEntity.status(500).body(Map.of("error", "WeChat API response missing openid or session_key"));
                }
            } catch (JsonProcessingException e) {
                // 如果响应不是 JSON 格式，记录日志并返回错误
                logger.error("Failed to parse WeChat API response as JSON: {}", responseBody);
                return ResponseEntity.status(500).body(Map.of("error", "Failed to parse WeChat API response"));
            }
        } catch (Exception e) {
            logger.error("Failed to get sessionId", e);
            return ResponseEntity.status(500).body(Map.of("error", "Failed to get sessionId: " + e.getMessage()));
        }
    }
    //获取历史信息
}
